# coding :utf-8
# __auth__ = Felix

import xmindparser
import xlwings as xw

# 定义一个容器来接受递归的结果
result = []

def get_tree(tree:dict,point = ''):
    """
    递归解析xmind文件
    :param tree: 处理过的xmind文件
    :param point: point为当前树节点的名称，层层向下传递
    :return: None
    """
    case_name = point + '_' + tree['title']
    try:
    # 判定当前树的下级分支是否大于1，有则递归遍历树
        if len(tree['topics']) > 1:
            # 如果存在下级分支，则递归遍历每一个分支
            for i in range(len(tree['topics'])):
                # 递归遍历树，传递上级树的节点名
                get_tree(tree['topics'][i],case_name)
    # 当前节点没有下一级目录了，则认为此处为一个测试案例了
    except KeyError:
        # 此时触底则开始生成case_name
        # 当前节点可能存在多个同级的节点，遍历生成多个案例
        for i in tree['topics']:
            try:
                # 获取树根部的下一个节点名称
                case_assert = i['topics'][0]['title']
            # 没有下级节点则抛出此错误
            except KeyError:
                case_assert = ''
            global result
            # 拼接案例名称后，将案例名称加入到容器result中
            f_name = case_name + '_' + i['title'] + '_' + case_assert
            # 删除掉遍历树导致的开头字符'_'
            f_name = f_name.strip('_')
            result.append(f_name)

def get_case_dict(xmind_file):
    dict_x = xmindparser.xmind_to_dict(xmind_file)
    # 获取到树状的xmind的字典结构数据
    dict_x = dict_x[0]['topic']
    get_tree(dict_x)
    return result

def creat_excel(filename):
    excel_app=xw.App(False,False)
    excel_file = excel_app.books.add()
    excel_file.save(filename)
    # 释放excel文件，防止资源占用导致的锁
    excel_file.close()
    excel_app.quit()

def wirte_excel(filename,value,sheet='sheet1',range ='A1'):
    app = xw.App(visible=False, add_book=False)
    wb = app.books.open(filename)
    wb.sheets[sheet].range(range).value=value
    wb.save()
    wb.close()


def append_value_excel(filename,value:list):
    app = xw.App(visible=True, add_book=False)
    wb = app.books.open(filename)
    wb.sheets['sheet1'].range(range).value = value
    wb.save()
    wb.close()
    app.quit()


def main(file_name):
    # 获取了案例名的list对象
    result_list = get_case_dict(file_name)
    # 遍历list获取案例名称
    # 生成测试案例的excel
    excel_name = file_name.strip('.xmind')
    excel_file = excel_name+'.xls'
    creat_excel(excel_file)
    for index in range(len(result_list)):
        wirte_excel(excel_file,result_list[index],range='A{}'.format(index+1))



if __name__ == '__main__':
    # xmind_file = r'需求10086.xmind'
    # print(get_case_dict(xmind_file))
    # creat_excel('./test.xlsx')
    # wirte_excel('./test.xlsx',value= '123')
    main(r'需求10086.xmind')
 
